#!/bin/bash

# 仅构建DLL模块的脚本（无需Qt）
# 适用于服务器环境展示核心功能

set -e

RED='\033[0;31m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
NC='\033[0m'

print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

print_info "构建文件扫描器DLL模块（无UI版本）"

# 检查基本依赖
if ! command -v g++ &> /dev/null; then
    print_error "g++ 未找到，请安装: sudo apt install build-essential"
    exit 1
fi

if ! command -v cmake &> /dev/null; then
    print_error "cmake 未找到，请安装: sudo apt install cmake"
    exit 1
fi

print_success "基本依赖检查通过"

# 清理并创建构建目录
if [ -d "build_dll" ]; then
    rm -rf build_dll
fi

mkdir build_dll
cd build_dll

print_info "创建仅DLL的CMakeLists.txt"

# 创建简化的CMakeLists.txt（仅构建DLL）
cat > CMakeLists.txt << 'EOF'
cmake_minimum_required(VERSION 3.10)
project(FileScannerDLL_Only)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

# 包含目录
include_directories(../Common)

# DLL源文件
set(DLL_SOURCES
    ../FileScannerDLL/FileScanner.cpp
    ../FileScannerDLL/DllExports.cpp
)

set(DLL_HEADERS
    ../FileScannerDLL/FileScanner.h
    ../Common/ScannerInterface.h
)

# 创建共享库
add_library(FileScanner SHARED ${DLL_SOURCES} ${DLL_HEADERS})

# 链接pthread
target_link_libraries(FileScanner pthread)

# 编译选项
target_compile_options(FileScanner PRIVATE -Wall -Wextra -O2)

# 测试程序
add_executable(test_scanner ../test_scanner.cpp)
target_link_libraries(test_scanner dl pthread)

# 设置输出目录
set_target_properties(FileScanner PROPERTIES
    LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}
)

set_target_properties(test_scanner PROPERTIES
    RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}
)
EOF

print_info "配置CMake项目"
cmake .

print_info "开始编译"
make -j$(nproc)

if [ $? -eq 0 ]; then
    print_success "编译成功！"
    
    print_info "生成的文件："
    ls -la libFileScanner.so test_scanner
    
    print_info "测试DLL功能"
    export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH
    ./test_scanner /home/lyt
    
else
    print_error "编译失败"
    exit 1
fi

print_success "DLL模块构建完成！"
print_info "可以将 libFileScanner.so 和相关头文件提供给面试官查看"